package edu.cmu.ece.ds.droidchat;

import android.app.TabActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import edu.cmu.ece.ds.droidchat.NetworkService.LocalBinder;
import edu.cmu.ece.ds.droidchat.model.StringConstants;
import edu.cmu.ece.ds.droidchat.model.UserInfo;
import edu.cmu.ece.ds.droidchat.view.LoggedInUserView;
import edu.cmu.ece.ds.droidchat.widget.ActionItem;
import edu.cmu.ece.ds.droidchat.widget.QuickActionList;
import edu.cmu.ece.ds.droidchat.widget.QuickActionList.OnListClickListener;

public class DroidChatTabActivity extends TabActivity {
    private final static String TAG = "DroidChatTabActivity";
    private NetworkService mService;
    private boolean mBound = false;
    private QuickActionList l;
    private ImageButton statusButton;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d(TAG, "---onCreate---");

        UserInfo myInfo = Toolbox.getMyInfo();

        if (myInfo == null) {
            Intent i = getIntent();
            /*
             * myInfo = new UserInfo(StringConstants.NO_USER_ID,
             * StringConstants.NO_USER_NAME, this.getResources()
             * .getDrawable(R.drawable.icon));
             * myInfo.setStatus(StringConstants.NO_USER_STATUS);
             */

            myInfo = new UserInfo(
                    i.getStringExtra(StringConstants.EXTRA_USER_NAME),
                    i.getStringExtra(StringConstants.EXTRA_USER_NAME));
            myInfo.setStatus("wahahaha");

            Toolbox.setMyInfo(myInfo);
        }
        myInfo.setStatus("wahahaha");
        setContentView(R.layout.main_tab_host);

        // prepare LoggedInUserView
        LoggedInUserView v = (LoggedInUserView) findViewById(R.id.logged_in_user_view);
        v.setUserInfo(myInfo);
        if (myInfo.getProfilePicture() == null) {
            Toolbox.imageDownloader.downloadToLoggedInUserInfoView(myInfo, v);
        } else {
            v.setUserIcon(myInfo.getProfilePicture());
        }

        // The activity TabHost
        TabHost tabHost = getTabHost();
        // Resusable TabSpec for each tab
        TabHost.TabSpec spec;
        // Reusable Intent for each tab
        Intent intent;

        // Create an Intent to launch an Activity for the tab (to be reused)
        intent = new Intent().setClass(this, NearbyUsersListActivity.class);

        // Initialize a TabSpec for each tab and add it to the TabHost
        spec = tabHost
                .newTabSpec(StringConstants.TAB_SPEC_NEARBY_USERS)
                .setIndicator(
                        buildIndicator(R.layout.tab_indicator_view_2,
                                R.string.nearby_users)).setContent(intent);
        tabHost.addTab(spec);

        // Do the same for the other tabs
        intent = new Intent().setClass(this, ChatSessionsListActivity.class);
        spec = tabHost
                .newTabSpec(StringConstants.TAB_SPEC_CHAT_SESSIONS)
                .setIndicator(
                        buildIndicator(R.layout.tab_indicator_view_2,
                                R.string.chat_sessions)).setContent(intent);
        tabHost.addTab(spec);

        intent = new Intent().setClass(this, SettingsActivity.class);
        spec = tabHost
                .newTabSpec(StringConstants.TAB_SPEC_SETTINGS)
                .setIndicator(
                        buildIndicator(R.layout.tab_indicator_view_2,
                                R.string.settings)).setContent(intent);
        tabHost.addTab(spec);
        getTabHost().setCurrentTabByTag(StringConstants.TAB_SPEC_NEARBY_USERS);

        // status dot imagebutton
        statusButton = (ImageButton) this.findViewById(R.id.logged_in_user_status_button);
        l = new QuickActionList(statusButton, LinearLayout.VERTICAL);
        l.addActionItem(new ActionItem(this,
                R.drawable.status_green_dot_transparent,
                R.string.status_available, ActionItem.HORIZONTAL));
        l.addActionItem(new ActionItem(this,
                R.drawable.status_orange_dot_transparent, R.string.status_idle,
                ActionItem.HORIZONTAL));
        l.addActionItem(new ActionItem(this,
                R.drawable.status_red_dot_transparent, R.string.status_busy,
                ActionItem.HORIZONTAL));
        l.addSeparator();
        l.addActionItem(new ActionItem(this, 0, R.string.status_logout,
                ActionItem.HORIZONTAL));
        l.setOnListClickListener(new OnListClickListener() {

            @Override
            public void onQuickActionListClicked(View contentView, int position) {
                switch (position) {
                case 0:
                    // available
                    statusButton
                            .setImageResource(R.drawable.status_green_dot_transparent);
                    break;
                case 1:
                    // idle
                    statusButton
                            .setImageResource(R.drawable.status_orange_dot_transparent);
                    break;
                case 2:
                    // busy
                    statusButton
                            .setImageResource(R.drawable.status_red_dot_transparent);
                    break;
                case 4:
                    // logout
                    Toast.makeText(DroidChatTabActivity.this,
                            "Logout comes here", Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        });
        statusButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                l.show();
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "---onStart---");

        Intent intent = new Intent(this, NetworkService.class);
        Log.d(TAG, "calling bindService()");
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    public void onStop() {
        super.onStop();
        Log.d(TAG, "---onStop---");
        Log.d(TAG, "---calling unbindService---");
        unbindService(mConnection);
    }

    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            // We've bound to TCPService, cast the IBinder and get TCPService
            // instance
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
            Log.d(TAG, mService.getPackageName());
            mBound = true;
            Log.d(TAG, "We've bound to TCPService");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;
        }
    };

    public NetworkService getService() {
        return mService;
    }

    public void onStatusChangeClick(View v) {

    }

    /**
     * Build a {@link View} to be used as a tab indicator, setting the requested
     * string resource as its label.
     */
    private View buildIndicator(int indicatorResId, int textResId) {
        final TextView indicator = (TextView) getLayoutInflater().inflate(
                indicatorResId, getTabWidget(), false);
        indicator.setText(textResId);
        return indicator;
    }
}
